/* Error handling: Takes a message, outputs it and closes the application. */

#include <allegro.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>

/* Syntax is a bit like printf:
 * bailout ("sdsd", "Player position: ", x, "/", y)
 * format parameter contains [printf format specifiers without %] and nothing else.
 * e.g. "sdsd" for string - int - string - int
 */
void bailout (char* format, ...)
{
	va_list ap;
	char* c;
	char wholemessage[256];
	char* writeptr = wholemessage;
	int e = errno;

	va_start(ap, format); 
	for (c = format; *c != '\0'; c++) {
		switch (*c) {
			case 's':
				sprintf (writeptr, "%s", va_arg(ap, const char*));
				break;
			
			case 'd':
				sprintf (writeptr, "%d", va_arg(ap, int));
				break;
			
			default:
				sprintf (writeptr, "[unknown arg %c]", *c);
				break;
		}
		writeptr += strlen(writeptr);
	}
	va_end(ap);
	
	fprintf (stderr, "Error: %s\n", wholemessage);
	fprintf (stderr, "\terrno = %d\n", e);
	
	allegro_exit ();
	exit (1);
}
